##
#   Project: BlueDUN
#            Internet connection manager for bluetooth devices.
#    Author: Fabio Castelli <muflone@vbsimple.net>
# Copyright: 2009 Fabio Castelli
#   License: GPL-2+
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation; either version 2 of the License, or (at your option)
#  any later version.
# 
#  This program is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
# 
# On Debian GNU/Linux systems, the full text of the GNU General Public License
# can be found in the file /usr/share/common-licenses/GPL-2.
##

import gtk
import gtk.glade
import gettext
import os
import handlepaths
import settings
import connection
import newconnection
import connect
import about
import rfcomms
from gettext import gettext as _

winConnections = None
tvwConnections = None
modelConnections = None
btnEdit = None
btnDelete = None
btnConnect = None

# Load domain for translation
for module in (gettext, gtk.glade):
  module.bindtextdomain(handlepaths.APP_NAME, handlepaths.getPath('locale'))
  module.textdomain(handlepaths.APP_NAME)

def listConnections():
  "List saved connections from confdir"
  modelConnections.clear()
  for iter_connection in os.listdir(settings.confdir):
    if iter_connection[-3:] == '.wv':
      deviceName = ''
      confFile = open(os.path.join(settings.confdir, iter_connection), 'r')
      for line in confFile:
        # Split key and value
        if '=' in line:
          key, value = map(str.strip, line[:-1].split('=', 2))
          # Save modem name
          if key == 'Modem':
            deviceName = value
            break
      confFile.close()
      modelConnections.append([iter_connection[:-3], deviceName])

def on_btnNew_clicked(widget, data=None):
  "Create a new connection"
  connection_name = newconnection.showWindow()
  if connection_name:
    connection.loadWindow()
    connection.showWindow(os.path.join(settings.confdir, '%s.wv' % connection_name))
    # Refresh the list
    listConnections()

def on_btnEdit_clicked(widget, data=None):
  "Edit the selected connection"
  iter = tvwConnections.get_selection().get_selected()[1]
  if iter:
    connection.loadWindow()
    confFile = os.path.join(settings.confdir, '%s.wv' % modelConnections[iter][0])
    connection.loadFile(confFile)
    connection.showWindow(confFile)
    # Refresh the list
    listConnections()

def on_btnDelete_clicked(widget, data=None):
  "Delete the selected connection"
  iter = tvwConnections.get_selection().get_selected()[1]
  if iter:
    os.remove(os.path.join(settings.confdir, '%s.wv' % modelConnections[iter][0]))
    # Refresh the list
    listConnections()

def on_btnAbout_clicked(widget, data=None):
  "Show the about dialog"
  about.showWindow()

def on_btnPorts_clicked(widget, data=None):
  "Show the ports dialog"
  rfcomms.showWindow()

def on_btnConnect_clicked(widget, data=None):
  "Connect the selected connection"
  iter = tvwConnections.get_selection().get_selected()[1]
  if iter:
    winConnections.destroy()
    connect.showWindow(modelConnections[iter][0])

def on_winConnections_delete_event(widget, data=None):
  "Quit"
  gtk.main_quit()

def on_tvwConnections_selection_changed(selection): 
  "Control sensitiveness of the buttons if a connection is selected"
  model, paths = selection.get_selected_rows()
  btnEdit.set_sensitive(len(paths) > 0)
  btnDelete.set_sensitive(len(paths) > 0)
  btnConnect.set_sensitive(len(paths) > 0)

def showWindow():
  "Show the connections dialog"
  global modelConnections
  global tvwConnections
  global btnEdit
  global btnDelete
  global btnConnect
  global winConnections

  gladeFile = gtk.glade.XML(
    fname=handlepaths.getPath('ui', 'connections.glade'),
    domain=handlepaths.APP_NAME)
  signals = {
    'on_winConnections_delete_event': on_winConnections_delete_event,
    'on_btnNew_clicked': on_btnNew_clicked,
    'on_btnEdit_clicked': on_btnEdit_clicked,
    'on_btnDelete_clicked': on_btnDelete_clicked,
    'on_btnConnect_clicked': on_btnConnect_clicked,
    'on_btnPorts_clicked': on_btnPorts_clicked,
    'on_btnAbout_clicked': on_btnAbout_clicked
  }
  gladeFile.signal_autoconnect(signals)
  gw = gladeFile.get_widget
  # Connections window
  winConnections = gw('winConnections')
  winConnections.set_icon_from_file(handlepaths.get_app_logo())
  winConnections.set_title(handlepaths.APP_TITLE)
  btnEdit = gw('btnEdit')
  btnDelete = gw('btnDelete')
  btnConnect = gw('btnConnect')
  btnPorts = gw('btnPorts')
  alignment = btnPorts.get_children()[0]
  box = alignment.get_children()[0]
  label = box.get_children()[1]
  label.set_text(_('RFCOMM ports'))

  tvwConnections = gw('tvwConnections')
  modelConnections = gtk.ListStore(str, str)
  tvwConnections.set_model(modelConnections)
  tvwConnections.get_selection().connect('changed', on_tvwConnections_selection_changed)

  # Column for port name
  cell = gtk.CellRendererText()
  column = gtk.TreeViewColumn(_('Connection name'))
  column.set_resizable(True)
  column.set_expand(True)
  column.pack_start(cell)
  column.set_attributes(cell, text=0)
  tvwConnections.append_column(column)

  # Column for address
  cell = gtk.CellRendererText()
  column = gtk.TreeViewColumn(_('Device name'))
  column.set_expand(True)
  column.pack_start(cell)
  column.set_attributes(cell, text=1)
  tvwConnections.append_column(column)
  listConnections()
  selectedConnection = None

  winConnections.show()
  gtk.main()
